package com.wmx.colone;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.io.*;

/**
 * @author wmx
 * @version 1.0
 * @date 2019/8/13 17:16
 * @description:
 */
@Getter
@Setter
@ToString
public class Student implements Serializable,Cloneable{
    private static final long serialVersionUID = -8024549003534774375L;
    private String name;
    private int age ;
    private Student friend;


    // 浅度克隆
    @Override
    protected Object clone() throws CloneNotSupportedException {

        return super.clone();
    }

    //深度克隆
    public Object deepClone(){
       /*
        对象序列化过程可以分为两步：
        第一: 将对象转换为字节数组
        第二: 将字节数组存储到磁盘*/
        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        ObjectInputStream objectInputStream = null;
        ByteArrayInputStream byteArrayInputStream = null;
        try {
            //序列化
            byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(this);
            byte [] a = byteArrayOutputStream.toByteArray();
            //反序列化 将字节数组转为对象
            byteArrayInputStream = new ByteArrayInputStream(a);
            objectInputStream = new ObjectInputStream(byteArrayInputStream);
            return objectInputStream.readObject();

        }catch (Exception e){
             e.printStackTrace();
        }finally {
            //for 循环中关闭流，如果其中一个出错后面的流就不能关闭
            close(byteArrayOutputStream,objectOutputStream,objectInputStream,byteArrayInputStream);
            try{
                objectInputStream.readObject(); //流关闭了报错
            }catch (Exception e){
                e.printStackTrace();
            }
          /*  close2(byteArrayInputStream);
            close2(objectInputStream);
            close2(byteArrayOutputStream);
            close2(objectOutputStream);*/

        }

        return null;
    }



    //关闭流 错误写法 ：for 循环中关闭流，如果其中一个出错后面的流就不能关闭 ,
    public static void close(Closeable... closeableList) {
        for (Closeable closeable : closeableList) {
            try {
                if (closeable != null) {
                    closeable.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //正确写法
    public <T extends java.io.Closeable> void close2(T t) {
        try {
            if (t != null) {
                t.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



 }
